﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

	<head>
		<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
		<title>Entities</title>
		<link href="bootstrap.min.css" type="text/css" rel="stylesheet" />
	</head>

	<body>

		<div class="document-contents">

			<p>Entities are one of the core concepts of DDD (Domain Driven Design). Eric Evans describe it as "<em>An object that is not fundamentally defined by its attributes, but rather by a thread of continuity and identity</em>". 
			So, entities have Id's and stored in a database. An entity is 
			generally mapped to a table for relational databases.</p>
			<h3 id="DocEntityClasses">Entity Class</h3>
			<p>In ASP.NET Boilerplate, Entities are derived from <strong>Entity </strong>
class. See the sample below:</p>

			<pre lang="cs">public class Person : Entity
{
    public virtual string Name { get; set; }

    public virtual DateTime CreationTime { get; set; }

    public Person()
    {
        CreationTime = DateTime.Now;
    }
}</pre>

			<p>
				<strong>Person</strong> class is defined as an entity. It has two properties. 
Also, Entity class defines an <strong>Id</strong> property. It's <strong>primary 
key </strong>of the Entity. So, name of primary keys of all Entities are same, 
it's <strong>Id</strong>.</p>
			<p>Type of Id (primary key) can be changed. It's
				<strong>int </strong>(Int32) by default. If you want to define another 
type as Id, you should explicitly declare it as shown below:</p>

			<pre lang="cs">public class Person : Entity&lt;long&gt;
{
    public virtual string Name { get; set; }

    public virtual DateTime CreationTime { get; set; }

    public Person()
    {
        CreationTime = DateTime.Now;
    }
}</pre>

			<p>Also, you can set it as string, Guid or something else.</p>
			<p>Entity class overrides <strong>equality</strong> operator (==) to easily 
check if two entities are equal (their Id is equal). It also defines the <strong>
IsTransient()</strong> method to check if it has an Id or not.</p>
			<h3>AggregateRoot Class</h3>
			<p>"<em>Aggregate is a pattern in Domain-Driven Design. A DDD 
			aggregate is a cluster of domain objects that can be treated as a 
			single unit. An example may be an order and its line-items, these 
			will be separate objects, but it's useful to treat the order 
			(together with its line items) as a single aggregate.</em>" (Martin 
			Fowler - see
			<a href="http://martinfowler.com/bliki/DDD_Aggregate.html" target="_blank">
			full description</a>)</p>
			<p>While ABP does not enforce you to use aggregates, you may want to 
			create aggregates and aggregate roots in your application. ABP 
			defines <strong>AggregateRoot</strong> class that extends Entity to 
			create aggregate root entities for an aggregate.</p>
			<h4>Domain Events</h4>
			<p>AggregateRoot defines <a href="EventBus-Domain-Events.html">
			<strong>DomainEvents</strong></a> collection to generate domain 
			events by the aggregate root class. These events are automatically 
			triggered just before the current <a href="Unit-Of-Work.html">unit 
			of work</a> is completed. Actually, any entity can generate domain 
			events by implementing <strong>IGeneratesDomainEvents</strong> 
			interface, but it's common (best practice) to generate domain events 
			in aggregate roots. That's why it's default for AggregateRoot but 
			not for Entity class.</p>
			<h3 id="DocConventionalInterfaces">Conventional Interfaces</h3>
			<p>In many application, similar entity properties (and database table fields) 
are used like CreationTime indicates that when this entity is created. ASP.NET 
Boilerplate provides some useful interfaces to make this common properties 
explicit and expressive. Also, this provides a way of coding common code for 
Entities which implement these interfaces.</p>
			<h4 id="DocAuditing">Auditing</h4>
			<p>
				<strong>IHasCreationTime</strong> makes it possible to use a common property 
for '<strong>creation time</strong>' information of an entity. ASP.NET Boilerplate automatically sets 
CreationTime to <strong>current time</strong> when an Entity is inserted 
into database which implements this interface.</p>
			<pre lang="cs">public interface IHasCreationTime
{
    DateTime CreationTime { get; set; }
}</pre>
			<p>Person class can be re-written as shown below by implementing IHasCreationTime interface:</p>
			<pre lang="cs">public class Person : Entity&lt;long&gt;, IHasCreationTime
{
    public virtual string Name { get; set; }

    public virtual DateTime CreationTime { get; set; }

    public Person()
    {
        CreationTime = DateTime.Now;
    }
}</pre>

			<p>
				<strong>ICreationAudited</strong> extens IHasCreationTime by adding&nbsp; 
				<strong>CreatorUserId</strong>:</p>
			<pre lang="cs">public interface ICreationAudited : IHasCreationTime
{
    long? CreatorUserId { get; set; }
}</pre>
			<p>ASP.NET Boilerplate automatically sets CreatorUserId to <strong>current 
user's id</strong> when saving a new entity. You can also implement ICreationAudited easily by deriving your entity from
				<strong>CreationAuditedEntity</strong> class. It has also a generic version for 
different type of Id properties.</p>
			<p>There is also similar interfaces for modifications:</p>
			<pre lang="cs">public interface IHasModificationTime
{
    DateTime? LastModificationTime { get; set; }
}

public interface IModificationAudited : IHasModificationTime
{
    long? LastModifierUserId { get; set; }
}</pre>
			<p>ASP.NET Boilerplate also automatically sets these properties when updating an 
entity. You just define them for your entity.</p>
			<p>If you want to implement all of audit properties, you can direcly implement
				<strong>IAudited </strong>interface:</p>
			<pre lang="cs">public interface IAudited : ICreationAudited, IModificationAudited
{

}</pre>
			<p>As a shortcut, you can derive from <strong>AuditedEntity </strong>class 
instead of direcly implementing <strong>IAudited</strong>. AuditedEntity class has 
also a generic version for different type of Id properties.</p>
			<p>Note: ASP.NET Boilerplate gets current user's Id from
				<a href="/Pages/Documents/Abp-Session">ABP Session</a>.</p>
			<h4 id="DocSoftDelete">Soft Delete</h4>
			<p>Soft delete is a commonly used pattern to mark an Entity as deleted instead 
of actually deleting it from database. For instace, you may not want to hard 
delete a User from database since it has many releations to other tables. 
				<strong>ISoftDelete</strong> interface is used for this purpose:</p>
			<pre lang="cs">public interface ISoftDelete
{
    bool IsDeleted { get; set; }
}</pre>
			<p>ASP.NET Boilerplate implements soft delete pattern out-of-the-box. When a 
soft-delete entity is being deleted, ASP.NET Boilerplate detects this, prevents 
deleting, sets IsDeleted as true and updates entity in the database. Also, it 
does not retrive (select) soft deleted entities from database, automatically 
filters them.</p>
			<p>If you use soft delete, you may also want to store information when an entity 
is deleted and who deleted it. You can implement <strong>IDeletionAudited</strong> interface that is shown below:</p>
			<pre lang="cs">public interface IDeletionAudited : ISoftDelete
{
    long? DeleterUserId { get; set; }

    DateTime? DeletionTime { get; set; }
}
			</pre>
			<p>IDeletionAudited extends ISoftDelete as you noticed. ASP.NET Boilerplate 
automatically sets these properties when an entity is deleted.</p>
			<p>If you want to implement all audit interfaces (creation, modification and 
deletion) for an entity, you can directly implement <strong>IFullAudited</strong> 
since it inherits all:</p>
			<pre lang="cs">public interface IFullAudited : IAudited, IDeletionAudited
{

}</pre>
			<p>As a shortcut, you can derive your entity from <strong>
FullAuditedEntity</strong> class that implements all.</p>
			<ul>
				<li>NOTE 1: All audit interfaces and classes have a generic version for defining navigation property 
to your <strong>User</strong> entity (like ICreationAudited&lt;TUser&gt; and 
				FullAuditedEntity&lt;TPrimaryKey, TUser&gt;).</li>
				<li>
				<p>NOTE 2: Also, all of them has an <strong>AggregateRoot</strong> 
				version, like AuditedAggregateRoot.</p>
				</li>
			</ul>
			<h4 id="DocActivePassive">Active/Passive Entities</h4>
			<p>Some entities need to be marked as Active or Passive. Then you may take 
action upon active/passive state of the entity. You can implement <strong>
IPassivable</strong> interface that is created for this reason. It defines
				<strong>IsActive</strong> property.</p>
			<p>If your entity will be active on first creation, you can set IsActive to true 
in the constructor.</p>
			<p>This is different than soft delete (IsDeleted). If an entity is soft deleted, 
it can not be retrieved from database (ABP prevents it as default). But, for 
active/passive entities, it's completely up to you to control getting entities.</p>
			<h3 id="DocIEntityInterfaces">Entity Change Events</h3>
			<p>ASP.NET Boilerplate automatically triggers certain events when an entity is 
inserted, updated or deleted. Thus, you can register to these events and perform 
any logic you need. See Predefined Events section in
				<a href="/Pages/Documents/EventBus-Domain-Events">event bus documentation</a> 
for more information.</p>
			<h3>IEntity Interfaces</h3>
			<p>Actually, <strong>Entity </strong>class implements <strong>IEntity </strong>interface (and <strong>Entity&lt;TPrimaryKey&gt;</strong> implements <strong>IEntity&lt;TPrimaryKey&gt;</strong>). 
If you do not want to derive from Entity class, you can implement these 
interfaces directly. There are also corresponding interfaces for other entity 
classes. But this is not the suggested way, unless you have a good 
reason to do not derive from Entity classes.</p>
			<h3>IExtendableObject Interface</h3>
			<p>ASP.NET Boilerplate provides a simple interface, 
			<strong>IExtendableObject</strong>, to easily associate <strong>arbitrary name-value data</strong> to 
			an entity. Consider this simple entity:</p>
			<pre lang="cs">public class Person : Entity, <strong>IExtendableObject</strong>
{
    public string Name { get; set; }

    <strong>public string ExtensionData { get; set; }</strong>

    public Person(string name)
    {
        Name = name;
    }
}</pre>
			<p><strong>IExtendableObject</strong> just defines <strong>ExtensionData</strong> 
			string property which is used to store <strong>JSON formatted</strong> name value 
			objects. Example:</p>
			<pre lang="cs">var person = new Person("John");

<strong>person.SetData("RandomValue", RandomHelper.GetRandom(1, 1000));
person.SetData("CustomData", new MyCustomObject { Value1 = 42, Value2 = "forty-two" });</strong></pre>
			<p>We can use any type of object as value to <strong>SetData</strong> method. When we 
			use such the code above, <strong>ExtensionData</strong> will be like 
			that:</p>
			<pre lang="js">{"CustomData":{"Value1":42,"Value2":"forty-two"},"RandomValue":178}</pre>
			<p>Then we can use <strong>GetData</strong> to get any value:</p>
			<pre lang="cs">var randomValue = person.<strong>GetData&lt;int&gt;("RandomValue")</strong>;
var customData = person.<strong>GetData&lt;MyCustomObject&gt;("CustomData")</strong>;
</pre>
			<p>While this technique can be very useful in some cases (when you 
			need to provide ability to dynamically add extra data to an entity), 
			you normally should use regular properties. Such a dynamic usage is 
			not type safe and explicit.</p>

		</div>

	</body>

</html>
